package com.yj.timecapsule.service.message.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.yj.timecapsule.common.context.LoginUserContext;
import com.yj.timecapsule.common.enums.ErrorCode;
import com.yj.timecapsule.common.error.BusinessException;
import com.yj.timecapsule.entity.user.Message;
import com.yj.timecapsule.entity.user.Users;
import com.yj.timecapsule.entity.user.vo.MessageUserVo;
import com.yj.timecapsule.entity.user.vo.MessageVo;
import com.yj.timecapsule.mapper.MessageMapper;
import com.yj.timecapsule.service.message.MessageService;
import com.yj.timecapsule.service.user.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author Sean
 * @CreateTime 2024-08-03  22:29
 * @Description
 * @Version 1.0
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private UserService userService;

    @Override
    public Integer clearAll(Long targetId) {
        if (targetId == null){
            throw new BusinessException(ErrorCode.FAIL);
        }
        Long userId = LoginUserContext.getId();
        int count = messageMapper.deleteBySenderIdAndReceiverId(userId,targetId);
        return count;
    }

    @Override
    public void del(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)){
            return;
        }
        messageMapper.deleteByIds(ids);
    }

    @Override
    public List<MessageVo> getMessages(Long targetId) {
        if (targetId == null) {
            throw new BusinessException(ErrorCode.FAIL);
        }
        Long senderId = LoginUserContext.getId();

        // 查询所有涉及 senderId 和 targetId 的消息
        List<Message> allMessages = messageMapper.selectAllBySenderIdOrReceiverId(senderId, targetId);

        // 创建一个 map 用来存储用户信息
        Map<Long, MessageUserVo> userMap = userService.getUserInfoMap(senderId, targetId);

        // 组织消息
        List<MessageVo> result = new ArrayList<>();
        for (Message message : allMessages) {
            MessageVo messageVo = new MessageVo();
            messageVo.setId(message.getId());
            messageVo.setContent(message.getContent());

            // 获取发送方信息
            MessageUserVo senderUserVo = userMap.get(message.getSenderId());
            messageVo.setSenderUserVo(senderUserVo);

            // 获取接收方信息
            MessageUserVo receiverUserVo = userMap.get(message.getReceiverId());
            messageVo.setReceiverUserVo(receiverUserVo);
            messageVo.setTimestamp(message.getSendTime());
            // 添加到结果列表
            result.add(messageVo);
        }

        return result;
    }



}
